package com.aspectj.aop.aspects;

import android.util.Log;
import android.view.View;

import com.aspectj.aop.annotation.SingleClick;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import java.util.HashMap;
import java.util.Map;

@Aspect
public class SingleClickAspect extends FatherAspect{
    private final String POINTCUT = "execution(@com.aspectj.aop.annotation.SingleClick * *(..))";
    private static Map<Integer, Long> mClickTargetMap = new HashMap<>();
    @Pointcut(POINTCUT)
    public void singleClickPointcut() {}

    @Around("singleClickPointcut() && args(view) && @annotation(singleClick)")
    public void onClick(ProceedingJoinPoint joinPoint, View view, SingleClick singleClick) throws Throwable {
        if(view != null && foundInTargetArray(singleClick, view)) {
            int key = view.hashCode();
            long now = System.currentTimeMillis();
            if(mClickTargetMap.containsKey(key)) {
                long lastClickTime = mClickTargetMap.get(key);

                if(now - lastClickTime < singleClick.value()) {
                    Log.v(TAG, " CLICK INTERVAL IS TOO SHORT");
                    return;
                }
            }
            mClickTargetMap.put(key, now);
        }
        joinPoint.proceed();
    }

    private boolean foundInTargetArray(SingleClick singleClick, View view){
        int[] targetIDs = singleClick.ids();
        for (int item: targetIDs) {
            if(item == view.getId()) {
                return true;
            }
        }
        return false;
    }
}